package com.vortex.cloud.sample.controller;

import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.core.DefaultExcelReader;
import com.github.liaochong.myexcel.utils.AttachmentExportUtil;
import com.github.liaochong.myexcel.utils.FileExportUtil;
import com.vortex.cloud.sample.domain.ArtCrowd;
import com.vortex.cloud.sample.domain.ArtCrowdRead;
import com.vortex.cloud.sample.domain.People;
import com.vortex.cloud.sample.dto.ArtCrowdDTO;
import com.vortex.cloud.sample.vo.ArtCrowdVo;
import com.vortex.cloud.sample.service.ArtCrowdService;
import com.vortex.cloud.sample.utils.MyExcelUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-10-20 周三
 * @time 16:01
 * @description
 */
@Tag(name = "myExcel导入导出", description = "myExcel导入导出")
@Validated
@CrossOrigin
@RestController
@RequestMapping("cloud/sample/api/v101/task/myexcel")
public class MyExcelController {

    @Resource
    private ArtCrowdService artCrowdService;

    @Operation(summary = "默认导入")
    @PostMapping(value = "/default/read/example", consumes = "multipart/form-data")
    public Boolean read(@Parameter(description = "文件", required = true) @RequestPart(required = false) MultipartFile file,
                        @Parameter(description = "开始读取数据的行索引") @RequestParam(required = false, defaultValue = "1") Integer startRowNum,
                        @Parameter(description = "开始读取数据的列索引") @RequestParam(required = false, defaultValue = "1") Integer startCellNum) throws IOException {
        List<ArtCrowdDTO> artCrowdDTOList = DefaultExcelReader.of(ArtCrowdDTO.class)
                .sheet(0)
                .rowFilter(row -> row.getRowNum() > 0)
                .read(file.getInputStream());

        for (ArtCrowdDTO artCrowdRead : artCrowdDTOList) {
            System.out.println(artCrowdRead + "=============================");
        }

//        List<ArtCrowd> artCrowdList = artCrowdDTOList.stream().map(entity -> {
//            ArtCrowd artCrowd = new ArtCrowd();
//            BeanUtils.copyProperties(entity, artCrowd);
//            artCrowd.setHobby("看妹子");
////            artCrowd.setPhoto(entity.getPhoto());
//            return artCrowd;
//        }).collect(Collectors.toList());

        List<ArtCrowd> artCrowdList = new ArrayList<>();
        for (ArtCrowdDTO artCrowdDTO : artCrowdDTOList) {
            ArtCrowd artCrowd = new ArtCrowd();
            BeanUtils.copyProperties(artCrowdDTO, artCrowd);
            artCrowd.setHobby("看妹子");

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            InputStream is = artCrowdDTO.getImage();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            is.close();
            bos.flush();
            byte[] result = bos.toByteArray();
            artCrowd.setPhoto(result);
            artCrowd.setImage(result);

            artCrowdList.add(artCrowd);
        }
        System.out.println("=============================------------------------------------");
//        for (ArtCrowd artCrowdRead : artCrowdList) {
//            System.out.println(artCrowdRead + "=============================");
//        }
        return artCrowdService.saveBatch(artCrowdList);
//        return true;
    }


    @Operation(summary = "默认导出")
    @GetMapping("/default/excel/example")
    public void defaultBuild(@RequestParam String fileName, HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
//        Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class)
//                .build(dataList);
//        AttachmentExportUtil.export(workbook, "艺术生信息-默认导出", response);

        MyExcelUtils.exportDefault(dataList, ArtCrowdVo.class, "艺术生信息-默认导出", response);
    }

    @Operation(summary = "导出-自定义样式")
    @GetMapping("/default/excel/example2")
    public void defaultBuild2(@RequestParam String fileName, HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
//        Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class)
//                .style("title->color:red", "cell->color:black", "font-size:40px", "background-color:##ABFF00", "text-align:center", "font-style:italic",
//                        "border-style:thin", "height: 20px", "width: 30px", "text-decoration: underline", "odd->color:pink", "odd->background-color:orange")
//                .build(dataList);
//        AttachmentExportUtil.export(workbook, "艺术生信息-自定义样式", response);

//        MyExcelUtils.exportCustomStyle(dataList, ArtCrowd.class, "艺术生信息-自定义样式", style, response);
        MyExcelUtils.exportCustomStyle(dataList, ArtCrowdVo.class, fileName, response);
    }

    @Operation(summary = "导出-加密")
    @GetMapping("/default/excel/example1")
    public void defaultBuild1(@RequestParam String fileName, HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
//        Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class).build(dataList);
//        AttachmentExportUtil.encryptExport(workbook, "艺术生信息-加密", response, "123456");

        MyExcelUtils.exportEncrypt(dataList, ArtCrowdVo.class, fileName, "123456", response);
    }

    @Operation(summary = "导出-无样式")
    @GetMapping("/default/noStyle/example")
    public void defaultBuildWithNoStyle(HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
//        Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class).noStyle().build(dataList);
//        AttachmentExportUtil.export(workbook, "艺术生信息-无样式", response);

        MyExcelUtils.exportWithNoStyle(dataList, ArtCrowdVo.class, "艺术生信息-无样式", response);
    }

    @Operation(summary = "导出-默认计算宽度等")
    @GetMapping("/default/autoWidth/example")
    public void defaultBuildWithAutoWidth(HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
//        Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class).widthStrategy(WidthStrategy.AUTO_WIDTH).build(dataList);
//        AttachmentExportUtil.export(workbook, "艺术生信息-默认计算宽度等", response);

        MyExcelUtils.exportWithAutoWidth(dataList, ArtCrowdVo.class, "艺术生信息-默认计算宽度等", response);
    }

    @Operation(summary = "导出-多表")
    @GetMapping("/default/continue/example")
    public void defaultBuildWithWorkbook(HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
//        Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class).widthStrategy(WidthStrategy.AUTO_WIDTH).build(dataList);
//        dataList = this.getDataList();
//        workbook = DefaultExcelBuilder.of(ArtCrowd.class, workbook).sheetName("sheet2").widthStrategy(WidthStrategy.NO_AUTO).build(dataList);
//        AttachmentExportUtil.export(workbook, "艺术生信息-多表", response);
        List<List<ArtCrowdVo>> lists = new ArrayList<>();
        lists.add(dataList);
        lists.add(dataList);
        lists.add(dataList);
        ArrayList<String> fileNames = new ArrayList<>();
        fileNames.add("艺术生信息-多表");
        fileNames.add("字表1");
        fileNames.add("字表2");
        MyExcelUtils.exportMultiTable(lists, fileNames, ArtCrowdVo.class, response);
    }

    @Operation(summary = "导出-动态导出")
    @PostMapping("/default/dynamic/example")
    public void defaultBuildDynamic(@RequestParam(required = false) List<String> titles,
                                    @RequestParam(required = false) List<String> orderList,
                                    @RequestParam(required = false) String password,
                                    @RequestParam(required = false, defaultValue = "数据表") String fileName, HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
//        ArrayList<String> titles = new ArrayList<>();
//        titles.add("姓名");
//        titles.add("年龄");
//        titles.add("性别");
//        List<String> order = new ArrayList<>();
//        order.add("name");
//        order.add("age");
//        order.add("gender");
        MyExcelUtils.exportDynamic(dataList, titles, ArtCrowdVo.class, fileName, orderList, password, response);
    }

    @Operation(summary = "导出-字段分组")
    @GetMapping("/default/group/example")
    public void defaultBuildGroup(@RequestParam String fileName, HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
        MyExcelUtils.exportGroup(dataList, ArtCrowdVo.class, People.class, fileName, response);
    }

    @Operation(summary = "导出-Map导出")
    @GetMapping("/default/map/example")
    public void defaultBuildMap(@RequestParam String fileName, HttpServletResponse response) throws Exception {
        List<ArtCrowdVo> dataList = this.getDataList();
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("a", "测试A");
        headerMap.put("b", "测试B");

        List<Map> dataMapList = new ArrayList<>();
        Map<String, Object> v1 = new HashMap<>();
        v1.put("a", "数据a1");
        v1.put("b", 3);

        Map<String, Object> v2 = new HashMap<>();
        v2.put("a", "数据a2");
        v2.put("b", 5);

        dataMapList.add(v1);
        dataMapList.add(v2);

        List<String> titles = new ArrayList(headerMap.values());
        List<String> orders = new ArrayList(headerMap.keySet());
        Workbook workbook = DefaultExcelBuilder.of(Map.class)
                .sheetName("sheet1")
                .titles(titles)
                .widths(10, 20)
                .fieldDisplayOrder(orders)
                .build(dataMapList);
        //本地文件导出
//        FileExportUtil.export(workbook, new File("H:\\zz.xlsx"));
        AttachmentExportUtil.export(workbook, fileName, response);
    }

    private List<ArtCrowdVo> getDataList() {
        List<ArtCrowdVo> dataList = new ArrayList<>(1000);
        for (int i = 0; i < 10; i++) {
            ArtCrowdVo artCrowd = new ArtCrowdVo();
            if (i % 2 == 0) {
                artCrowd.setId(i + 1);
                artCrowd.setName("Tom");
                artCrowd.setAge(19);
                artCrowd.setGender("Man");
                artCrowd.setPaintingLevel("一级证书");
                artCrowd.setDance(false);
                artCrowd.setAssessmentTime(LocalDateTime.now());
                artCrowd.setHobby("看妹子");
                artCrowd.setUrl("百度->https://www.baidu.com/");
                artCrowd.setImage(new File("H:\\images\\22.jpg"));
                artCrowd.setOptions(Arrays.asList("鞠婧祎", "高圆圆", "周迅", "章子怡", "李冰冰"));
            } else {
                artCrowd.setId(i + 1);
                artCrowd.setName("Marry");
                artCrowd.setAge(18);
                artCrowd.setGender("Woman");
                artCrowd.setPaintingLevel("一级证书");
                artCrowd.setDance(true);
                artCrowd.setAssessmentTime(LocalDateTime.now());
                artCrowd.setHobby("钓鱼");
                artCrowd.setUrl("百度->https://www.baidu.com/");
                artCrowd.setImage(new File("H:\\images\\22.jpg"));
                artCrowd.setOptions(Arrays.asList("章子怡", "鞠婧祎", "高圆圆", "周迅", "李冰冰"));
            }
            dataList.add(artCrowd);
        }
        return dataList;
    }
}
